package com.hank.swagger.service.doc.config;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.stereotype.Component;


/**
 * 阿波罗刷新组件
 *
 * @author hank
 */
@Component
@Slf4j
public class ApolloConfigChangeRefresher {

    private final SwaggerResourceConfig swaggerResourceConfig;

    private final RefreshScope refreshScope;


    public ApolloConfigChangeRefresher(RefreshScope refreshScope, SwaggerResourceConfig swaggerResourceConfig) {
        this.refreshScope = refreshScope;
        this.swaggerResourceConfig = swaggerResourceConfig;
    }

    @ApolloConfigChangeListener
    public void onChangeGray(ConfigChangeEvent changeEvent) {
        refreshProperties(changeEvent, "appApiConfig");
    }

    /**
     * 刷新的核心代码
     *
     * @param changeEvent
     * @param beanName
     */
    private void refreshProperties(ConfigChangeEvent changeEvent, String beanName) {
        log.info("Refreshing properties! namespace: {}, changedKeys: {}, beanName: {}", changeEvent.getNamespace(), changeEvent.changedKeys(), beanName);
        try {
            refreshScope.refresh(beanName);
        } catch (Exception e) {
            log.error("refreshScope.refresh error", e);
        }
        swaggerResourceConfig.initEurekaApps();
        log.info("properties refreshed!");
    }

}